/**
 * 准备函数
 */
var operateRight = new Object();
$(document).ready(function() {
	
	// 加载权限
	loadRight();
	
	// 加载表格
	queryMaterial();
	
	// 绑定函数
	$("#createButton").bind("click", showCreateMaterialDialog);
	$("#confirmCreateMaterialButton").bind("click", confirmCreateMaterial);
	$("#confirmModifyMaterialButton").bind("click", confirmModifyMaterial);
	
	layui.use(['form', 'laydate'], function() {
		$form = layui.form;
		$form.on('select(cType)', function(data) {
			if (data.value != FileType.IMAGE_V) {
				$('.imagePreItem').show();
			}else{
				$('.imagePreItem').hide();
			}
			
			$("#matUrl,#matPreUrl,#name,#filemd5,#fileSize,#duration,#width,#height").val("");
			var objPre = document.getElementById('cMaterialPreviewFile'); 
			objPre.outerHTML = objPre.outerHTML;
			$("#fileDivListPre").html("");
			
			var obj = document.getElementById('cMaterialFile'); 
			obj.outerHTML = obj.outerHTML;
			$("#fileDivList").html("");
			
			updateLayuiForm();
		});
	});
	
	$(".search-main-top a").click(function(){
		var $this = $(this);
		if($this.hasClass("on")){
			$this.removeClass("on");
			$this.siblings('a').eq(0).addClass("on");
		}else{
			$this.siblings().removeClass("on");
			$this.addClass("on");
		}
		queryMaterial();
	});
});

/**
 * 加载权限
 */
function loadRight() {
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
}

/**
 * 查询
 */
function queryMaterial(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	$(".channelId").each(function(){
		var channelId = $(this).attr('data-v');
		if($(this).hasClass("on") && Utils.isNotNull(channelId)){
			data.channelId = channelId;
		}
	});
	
	$(".categoryId").each(function(){
		var categoryId = $(this).attr('data-v');
		if($(this).hasClass("on") && Utils.isNotNull(categoryId)){
			data.categoryId = categoryId;
		}
	});
	
	$(".type").each(function(){
		var type = $(this).attr('data-v');
		if($(this).hasClass("on") && Utils.isNotNull(type)){
			data.type = type;
		}
	});
	
	$(".price").each(function(){
		var price = $(this).attr('data-v');
		if($(this).hasClass("on") && Utils.isNotNull(price)){
			var arr = price.split("-");
			data.beginPrice = arr[0];
			data.endPrice = arr[1];
		}
	});
	
	$(".status").each(function(){
		var status = $(this).attr('data-v');
		if($(this).hasClass("on") && Utils.isNotNull(status)){
			data.status = status;
		}
	});
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);

	// 调用接口
	var response = callInterface("post", "saas/shop/queryContent", data, false);
	if (response.code == 0) {
		// 清空分页
		$("#pageDiv").html("");

		var materialSpan = "";
		var count = response.data.totalCount;
		var list = response.data.list;
		if (list != null && list.length > 0) {
			materialSpan += '<section>';
			materialSpan += '<div class="wf-container">';
			//循环item
			for ( var i in list) {
				if(Utils.isNull(list[i].previewUrl)){
					continue;
				}
				materialSpan += '<div class="wf-box">';
				materialSpan += '<a href="javascript:void(0);" onclick="showMaterialDetailDialog(\'' + list[i].id + '\',\'' + list[i].title + '\');">';
				materialSpan += "<img style='width:200px;height:200px' src=\"" + list[i].previewUrl + Global.IMG_SiZE_TWO_H + "\"></a>";
				materialSpan += '<div class="content"><p>';
				materialSpan += '<font style="font-weight:bold">';
				materialSpan += '<font style="font-weight:bold" title="'+list[i].title+'">' + cutString(list[i].title,16) + '</font><br>';
				materialSpan += '<font style="font-weight:bold"> 渠道：</font>'+list[i].channelName+'<br>';
				materialSpan += '<font style="font-weight:bold"> 文件类型：</font>' + getFileTypeName(list[i].type)  + '<br>';
				materialSpan += '<font style="font-weight:bold"> 更新时间：</font>' + list[i].createdTime + '<br>';
				materialSpan += '<div class="clear">';
				var price = Utils.toFormatDecimal(list[i].price,2);
				if(price == 0 || price == 0.00){
					price = "免费";
				}else{
					price = "￥" + price;
				}
				materialSpan += '<div><font style="display:inline-block;width:50%;text-align:left;color:red;">' + price + '</font>';
				// 删除
				if (operateRight.deleteRight == 1){
					materialSpan += '<span style="display:inline-block;width:50%;text-align:right;"><a href="javascript:void(0);"class="zengzhi delete" onclick="deleteMaterial(\''
						+ list[i].id + '\');">删除</a>';
				}
				// 编辑
				if (operateRight.modifyRight == 1 && list[i].auditStatus != MaterialAuditStatus.PASS_AUDIT_V){
					materialSpan += '&nbsp;&nbsp;<a href="javascript:void(0);" class="zengzhi delete" onclick="showModifyMaterialDialog(\''
						+ list[i].id + '\');">编辑</a></span></div>';
				}
				materialSpan += '</div>';
				materialSpan += '</p></div></div>';
			}
			materialSpan += '</div></section>';
			$('#materialDiv').html(materialSpan);
			var waterfall = new Waterfall({ minBoxWidth: 200 });
			
			// 调用分页
			layui.use(['laypage'], function() {
				var laypage = layui.laypage;
				laypage.render({
					elem : 'pageDiv',
					// pages : pages,
					curr : pageIndex || 1, // 当前页
					count : count,
					limit : pageSize,
					skip : true, // 是否开启跳页
					layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
					groups : 5, // 连续显示分页数
					jump : function(obj, first) { // 触发分页后的回调
						if (!first) {
							queryMaterial(obj.curr, obj.limit);
						}
					}
				});
			});
		}else{
			$('#materialDiv').html("无素材!");
		}
	}
}

/**
 * 显示上传素材对话框
 */
function showCreateMaterialDialog() {
	$("#createMaterialDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#createMaterialForm')[0].reset();
	
	// 初始化创建数据
	initCreateData();
}

function initCreateData(){
	// 初始化文件选择相关
	$("#cType").val(FileType.IMAGE_V);
	$('.imagePreItem').hide();
	$("#matUrl,#matPreUrl,#name,#filemd5,#fileSize").val("");
	$("#duration,#width,#height,#cChannelId,#cCategoryId").val("");
	
	var objPre = document.getElementById('cMaterialPreviewFile'); 
	objPre.outerHTML = objPre.outerHTML;
	$("#fileDivListPre").html("");
	
	var obj = document.getElementById('cMaterialFile'); 
	obj.outerHTML = obj.outerHTML;
	$("#fileDivList").html("");
	
	updateLayuiForm();
}

/**
 * 确认上传素材
 */
function confirmCreateMaterial() {
	
	if(videoCodeErr){
		showAlert("文件格式有误，请上传编码格式为h264的视频文件！");
		return;
	}
	
	var formdata = new FormData();
    
    var type = $("#cType").val();
    if(Utils.isNotNull(type)){
    	formdata.append("type", type);
    }else{
    	showAlert("请选择素材类型!");
		return false;
    }
    
    if(type == FileType.VIDEO_V){
    	var previewUrl = $("#matPreUrl").val();
    	if(Utils.isNotNull(previewUrl)){
        	formdata.append("previewUrl", previewUrl);
        }else{
        	showAlert("请上传预览图!");
    		return false;
        }
    }
    
    var url = $("#matUrl").val();
	if(Utils.isNotNull(url)){
    	formdata.append("url", url);
    }else{
    	showAlert("请上传素材!");
		return false;
    }
    
    var title = $("#cTitle").val();
    if(Utils.isNotNull(title)){
    	formdata.append("title", title);
    }else{
    	showAlert("标题不能为空!");
		return false;
    }
    
    var channelId = $("#cChannelId").val();
    if(Utils.isNotNull(channelId)){
    	formdata.append("channelId", channelId);
    }else{
    	showAlert("渠道不能为空!");
		return false;
    }
    
    var categoryId = $("#cCategoryId").val();
    if(Utils.isNotNull(categoryId)){
    	formdata.append("categoryId", categoryId);
    }else{
    	showAlert("分类不能为空!");
		return false;
    }
    
    var price = $("#cPrice").val();
    if(Utils.isNotNull(price)){
    	formdata.append("price", price);
    }else{
    	showAlert("价格不能为空!");
		return false;
    }
    
    var description = $("#cDescription").val();
    if(Utils.isNotNull(description)){
    	formdata.append("description", description);
    }else{
    	showAlert("内容简介不能为空!");
		return false;
    }
    
    formdata.append("name", $("#name").val());
    formdata.append("filemd5", $("#filemd5").attr('data-md5'));
	formdata.append("fileSize", $("#fileSize").val());
	formdata.append("duration", $("#duration").val());
	formdata.append("width", $("#width").val());
	formdata.append("height", $("#height").val());
	
	$.ajax({
		type : 'POST',
		url : 'saas/shop/createContent',
		data : formdata,
		dataType : "json",
		cache : false,
		contentType : false,
		processData : false,
		success : function(response) {
			if (response.code == 0) {
				
				// 刷新
				showMsg("操作成功!");
				queryMaterial(currPage);
			} else {
				showErrorMsg(response.code, response.message);
			}
			$('#createMaterialDialog').modal("hide");
		},
		error : function(data) {
			showErrorMsg(data.code, data.message);
		}
	});
}

/**
 * 触发选择文件事件
 * 
 * @param selectFileId
 */
function doContTriggerClick(selectFileId){
	$("#"+selectFileId).trigger("click");
}

/**
 * 上传素材图片并预览 
 * inputFileId	:	图片文件 
 * fileShowDiv	:	图片预览 
 * fileType	:	文件类型(1:图片 2:视频 3:音频 4:网页 5:其他)
 */
var fuIndex = 0;
var fileObjs;
function selectFileToOss(inputFileId, fileShowDiv, fileType, isPreImg) {
	
	var materialType;
	if(isPreImg){
		materialType = FileType.IMAGE_V;
	}else{
		materialType = $("#"+fileType).val();
	}
	
	//文件种类
	var suppotFormat = getFileSuffix(materialType);
	//校验文件合法性
	fileObjs = document.getElementById(inputFileId).files[0];
	var fileName = fileObjs.name;
	//转换大小写
	var suffix = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase(); 
	if (suppotFormat.indexOf(suffix) == -1) {
		Utils.showCustomTips(inputFileId, 1, '文件格式错误，支持的格式为：' + suppotFormat, '#000', '#ffe74c', 5);
		fileObjs.outerHTML = fileObjs.outerHTML; 
		return false;
	}
	
	var typeFlag = isPreImg ? FileType.IMAGE_PRE_V : materialType;
	var isOk = checkUploadFileSize(typeFlag, getFileSizeMByB(fileObjs.size));
	if(!isOk){
		if(isPreImg){
			Utils.showCustomTips(inputFileId, 1, "预览图文件超出限制大小，应≤" + FileType.IMAGE_PRE_MAX_SIZE + "M", '#000', '#ffe74c', 5);
			return false;
		}else{
			Utils.showCustomTips(inputFileId, 1, "文件超出限制大小：(" + getMaxFileSizeDes() + ")", '#000', '#ffe74c', 5);
			return false;
		}
	}
	
	// 图片
	if(materialType != FileType.VIDEO_V){
		createLoadingDiv();
		fuIndex++;
		// 初始化、进度条(默认隐藏)、文件名
		var fileDiv = "";
	    fileDiv += "	<div class='fileItem file-item fl materialType_"+fuIndex+"' data-isPre='"+isPreImg+"' data-index='"+fuIndex+"'>";
	    fileDiv += "		<div class='item-img'>";
	    fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\"image/fileLogo/"+suffix+".jpg\" />";
	    fileDiv += "		</div>";
	    fileDiv += "		<div class='progress'>";
	    fileDiv += "			<div class='solidBar fileProgress_"+fuIndex+"' style='width:100%' ></div>";
	    fileDiv += "			<div class='progressTit fileProgressTit_"+fuIndex+"'>待上传...</div>";
	    fileDiv += "		</div>";
	    fileDiv += "	</div>";
	    $("#"+fileShowDiv).html(fileDiv);
	    
	    // 获取请求参数
		var client = getOssWrapper();
		// 获取文件MD5
		getFileMd5($("#filemd5"), fileObjs);
		// 执行请求
		client.multipartUpload(getStoreAs(fileObjs), fileObjs,{
			progress: function* (percent, cpt) {  
				percent =  Utils.toFormatDecimal(percent*100,0);
				setFileProgress(percent, fuIndex);
			}
		}).then(function (result) {
			var fileUrl = handleOssUrl(result.res.requestUrls[0]);
	        if(isPreImg){
				$("#matPreUrl").val(fileUrl);
			}else{
				getImgInfo(fileUrl).then(imgInfo => {
				    //console.log("imgInfo:"+imgInfo);
				    $("#width").val(imgInfo.width);
				    $("#height").val(imgInfo.height);
				});
				$("#matUrl").val(fileUrl);
				$("#fileSize").val(fileObjs.size);
				$("#name").val(fileName);
			}
	        
			closeLoadingDiv();
		}).catch(function (err) {
			closeLoadingDiv();
		});
	}else{
		// 获取本地视频信息
		$("#myVideo").prop("src",  URL.createObjectURL(fileObjs));
	}
}


/**
 * 获取视频信息
 * 
 * @returns
 */
var videoCodeErr = false;
function getVideoDes(){
	var vDuration = $("#myVideo").get(0).duration;
	var vWidth = $("#myVideo").get(0).videoWidth;
	var vHeight = $("#myVideo").get(0).videoHeight;
	if(Utils.isUndefined(vDuration) ||  Utils.isUndefined(vWidth) || Utils.isUndefined(vHeight) || vWidth == 0 || vHeight == 0){
		videoCodeErr = true;
		showAlert("文件格式有误，请上传编码格式为h264的视频文件！");
		return;
	}else{
		videoCodeErr = false;

		createLoadingDiv();
		fuIndex++;
		// 初始化、进度条(默认隐藏)、文件名
		var fileDiv = "";
	    fileDiv += "	<div class='fileItem file-item fl materialType_"+fuIndex+"' data-isPre='0' data-index='"+fuIndex+"'>";
	    fileDiv += "		<div class='item-img'>";
	    fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\"image/fileLogo/mp4.jpg\" />";
	    fileDiv += "		</div>";
	    fileDiv += "		<div class='progress'>";
	    fileDiv += "			<div class='solidBar fileProgress_"+fuIndex+"' style='width:100%' ></div>";
	    fileDiv += "			<div class='progressTit fileProgressTit_"+fuIndex+"'>待上传...</div>";
	    fileDiv += "		</div>";
	    fileDiv += "	</div>";
	    $("#fileDivList").html(fileDiv);
	    
	    // 获取请求参数
		var client = getOssWrapper();
		// 获取文件MD5
		getFileMd5($("#filemd5"), fileObjs);
		// 执行请求
		client.multipartUpload(getStoreAs(fileObjs), fileObjs,{
			progress: function* (percent, cpt) {  
				percent =  Utils.toFormatDecimal(percent*100,0);
				setFileProgress(percent, fuIndex);
			}
		}).then(function (result) {
			var fileUrl = handleOssUrl(result.res.requestUrls[0]);
			$("#matUrl").val(fileUrl);
			$("#fileSize").val(fileObjs.size);
			$("#name").val(fileObjs.name);
	        
			closeLoadingDiv();
		}).catch(function (err) {
			closeLoadingDiv();
		});
	}
	
    $("#duration").val(Utils.toFormatDecimal(vDuration,0));
    $("#width").val(vWidth);
    $("#height").val(vHeight);
	closeLoadingDiv();
}

/**
 * 显示修改对话框
 */
function showModifyMaterialDialog(id) {
	// 显示对话框
	$("#modifyMaterialDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyMaterialForm')[0].reset();
	
	// 查询素材详情
	getMateriamDetail(id);
}

function getMateriamDetail(id){
	// 调用接口
	var response = callInterface("post", "saas/shop/getContent", {
		'id' : id
	}, false);
	if (response.code == 0) {
		
		var data = response.data;
		
		$("#mId").val(data.id);
		$("#mChannelName").text(data.channelName);
		$("#mTypeName").text(getFileTypeName(data.type));
		$("#mFileSize").text(getFileSizeAuto(data.fileSize));
		$("#mResolutionName").text(data.width+"*"+data.height);
		if(data.type == FileType.IMAGE_V){
			$("#mDuration").parent().parent().hide();
			$("#mMaterialFile").prop('src',data.url);
		}else{
			$("#mDuration").parent().parent().show();
			$("#mMaterialFile").prop('src',data.previewUrl);
		}
		$("#mDuration").text(data.duration);
		
		$("#mTitle").val(data.title);
		$("#mPrice").val(data.price);
		$("#mCategoryId").val(data.categoryId);
		$("#mDescription").val(data.description);
		$("#mAuditStatus").val(data.auditStatus);
		updateLayuiForm();
		
	} else {
		showErrorMsg(response.code, response.message);
	}
}


/**
 * 确认编辑素材
 */
function confirmModifyMaterial() {
	
	var formdata = new FormData();
	 var id = $("#mId").val();
	 formdata.append("id", id);
    
    var title = $("#mTitle").val();
    if(Utils.isNotNull(title)){
    	formdata.append("title", title);
    }else{
    	showAlert("标题不能为空!");
		return false;
    }
    
    var categoryId = $("#mCategoryId").val();
    if(Utils.isNotNull(categoryId)){
    	formdata.append("categoryId", categoryId);
    }else{
    	showAlert("分类不能为空!");
		return false;
    }
    
    var price = $("#mPrice").val();
    if(Utils.isNotNull(price)){
    	formdata.append("price", price);
    }else{
    	showAlert("价格不能为空!");
		return false;
    }
    
    var description = $("#mDescription").val();
    if(Utils.isNotNull(description)){
    	formdata.append("description", description);
    }else{
    	showAlert("内容简介不能为空!");
		return false;
    }
    
    var auditStatus = $("#mAuditStatus").val();
    if(MaterialAuditStatus.PENDING_AUDIT_V == auditStatus || MaterialAuditStatus.NOPASS_AUDIT_V == auditStatus){
    	auditStatus = MaterialAuditStatus.PENDING_AUDIT_V;
    }else{
    	showAlert("当前内容不允许编辑!");
		return false;
    }
    formdata.append("auditStatus", auditStatus);
    
	$.ajax({
		type : 'POST',
		url : 'saas/shop/modifyContent',
		data : formdata,
		dataType : "json",
		cache : false,
		contentType : false,
		processData : false,
		success : function(response) {
			if (response.code == 0) {
				
				// 刷新
				showMsg("操作成功!");
				queryMaterial(currPage);
			} else {
				showErrorMsg(response.code, response.message);
			}
			$('#modifyMaterialDialog').modal("hide");
		},
		error : function(data) {
			showErrorMsg(data.code, data.message);
		}
	});
}

/**
 * 删除
 */
function deleteMaterial(id) {
	// 询问框
	layer.confirm('确定删除该内容吗？', {
	  offset :'20px',btn: ['确定','取消'] //按钮
	}, function(){
		// 调用接口
		var response = callInterface("post", "saas/shop/deleteContent", {"id" : id} , false);
		if (response.code == 0) {
			showMsg('操作成功!');

			// 刷新
			queryMaterial(currPage);
		} else {
			showErrorMsg(response.code, response.message);
		}
	}, function(){
		return;
	});
}